package com.ghr.controller;

import com.alibaba.fastjson.JSON;
import com.ghr.common.ListResult;
import com.ghr.common.Result;
import com.ghr.common.ResultUtils;
import com.ghr.model.entity.Fruit;
import com.ghr.utils.ElasticSearchUtil;
import com.ghr.utils.JsonUtils;
import org.elasticsearch.action.search.ClearScrollRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchScrollRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.core.CountRequest;
import org.elasticsearch.client.core.CountResponse;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@RestController
@RequestMapping("/es")
public class EsController {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @RequestMapping("/all")
    public Result<ListResult<Fruit>> getAll() throws IOException {
        CountResponse countResponse = restHighLevelClient.count(new CountRequest("fruit"), RequestOptions.DEFAULT);
        long count = countResponse.getCount();
        System.out.println("总记录数：" + count);


        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.size(5000); // 每次查询5000条记录
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());

        // 创建滚动查询请求
        SearchRequest scrollRequest = new SearchRequest("fruit");
        scrollRequest.scroll(TimeValue.timeValueMinutes(1));
        scrollRequest.source(searchSourceBuilder);

        // 执行滚动查询
        SearchResponse scrollResponse = restHighLevelClient.search(scrollRequest, RequestOptions.DEFAULT);
        // 获取初始的搜索结果
        SearchHits hits = scrollResponse.getHits();

        // 处理滚动查询的结果
        List<Fruit> allFruitRecords = new ArrayList<>();
        while (hits.getHits().length > 0) {
            for (SearchHit hit : hits) {
                Fruit fruit = JSON.parseObject(hit.getSourceAsString(), Fruit.class);
                allFruitRecords.add(fruit);
            }
            // 使用 scrollId 获取下一批结果
            String scrollId = scrollResponse.getScrollId();
            scrollResponse = restHighLevelClient.scroll(new SearchScrollRequest(scrollId).scroll(TimeValue.timeValueMinutes(1)), RequestOptions.DEFAULT);
            hits = scrollResponse.getHits();
        }

        List<Fruit> list = allFruitRecords.stream().sorted(Comparator.comparing(Fruit::getId).reversed()).toList();
        System.out.println("=================");
        System.out.println("查询结果：" + JsonUtils.toJsonUnchecked(list));

        // 清除滚动上下文
        ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
        clearScrollRequest.addScrollId(scrollResponse.getScrollId());
        restHighLevelClient.clearScroll(clearScrollRequest, RequestOptions.DEFAULT);

        return ResultUtils.success(new ListResult<>(list, list.size()));
    }
}
